import pool from '../db/index.js'

//开始新的对话(已登录，需要‘用户ID’、‘对话的角色’)
export async function newDialog(req,res){
    try {
        const { id,dialogRole } = req.body;
        const [result] = await pool.query(
            'INSERT INTO conversation (user_id,AI_role) VALUES(?,?)',
            [id,dialogRole]
        );
        
        const [newConversation] = await pool.query(
            `SELECT id,AI_role,created_at FROM conversation
                WHERE id = ?`,
            [result.insertId]
        )

        return res.status(200).json({
            code:200,
            msg:'成功创建新的对话',
            data:newConversation
        })

    } catch (error) {
        return res.status(500).json(error.message)
    }
}

//查询用户当前建立的所有对话(已登录，需要‘用户ID’)
export async function allConversation(req,res){
    try{
        const {id} = req.query;
        const [result] = await pool.query(
            `SELECT id,AI_role,created_at FROM conversation
             WHERE user_id = ?`,
             [id]
        )

        if(!result[0]){
            return res.status(200).json({
                code:200,
                msg:'您还没有拜访过任何角色',
                data:{}
            })
        }

        return res.status(200).json({
            code:200,
            msg:'获取全部对话成功',
            data:result
        })

    }catch(error){
        return res.status(500).json(error.message)
    }
    
}

//查询当前进行的对话（已登录，需要‘对话ID’）
export async function CheckConversation(req,res){
    try{

        const {id}=req.params;
        const [conversationDetail] =await pool.query(
            `SELECT * FROM conversation WHERE id =?`,
            [id]
        )

        if(conversationDetail.length === 0){
            return res.status(404).json('该对话不存在或者已经删除')
        }

        return res.status(200).json({
            code:200,
            msg:'成功获取对话细节',
            data:conversationDetail[0]
        })

    }catch(error){
        return res.status(500).json(error.message)
    }
}

//删除当前对话(已登录，需要‘删除对话的ID’)
export async function DeleteConversation(req,res){
    try{
        const {id} = req.params;

        const [result]=await pool.query(
            `DELETE FROM conversation 
                WHERE id = ?`,
                [id]
        )

        return res.status(200).json({
            code:200,
            msg:'删除成功',
            data:{
                result:result
            }
        })

    }catch(error){
        return res.status(500).json(error.message)
    }
    
}

//获取与该AI对话的历史记录，主要用于首次打开对话界面(已登录，需要‘进行对话的ID’)
export async function historyMessage(req,res){
    try {
        
        const {id} = req.query;
        const [historyMessage]=await pool.query(
            `SELECT id,sender,content,send_time FROM messages
            WHERE conversation_id = ?`,
            [id]
        )

        if(!historyMessage[0]){
            return res.status(200).json({
                code:200,
                msg:'还没有进行过聊天',
                data:0
            })
        }

        return res.status(200).json({
            code:200,
            msg:'成功获取聊天记录',
            data:historyMessage
        })

    } catch (error) {
        return res.status(500).json('聊天记录获取失败')
    }
    
}


//与AI对话(已登录，需要‘进行对话的ID’、‘对话的内容’)
export async function Dialog(req,res){
    try{

        const {conversationId,userMessage}=req.body;
        const [targetConversation] = await pool.query(
            'SELECT * FROM conversation WHERE id = ?',
            [conversationId]
        );

        if(targetConversation.length===0){
            return res.status(404).json('会话过期或者不存在')
        }

        const [historyMessage]= await pool.query(
            `SELECT c.AI_role,m.sender,m.content,m.send_time FROM conversation c 
                JOIN messages m ON c.id = m.conversation_id
                WHERE c.id = ?
                ORDER BY m.send_time ASC
            `,[conversationId]
        )

        const historyMessageSim=historyMessage.map(msg=>{
            const {sender,content} = msg;
            return {role:sender,content:content }
        })

        const response= await fetch('https://openai.qiniu.com/v1/chat/completions',{
            method:'POST',
            headers:{
                Authorization:`Bearer ${process.env.OPENAI_API_KEY}`,
                'Content-Type': 'application/json'
            },
            body:JSON.stringify({
                stream:false,
                model:'deepseek-v3.1',
                messages: [
                    { role: 'system', content: `扮演${targetConversation[0].AI_role}与目标进行对话` }, // 系统提示（定义AI角色）
                    ...historyMessageSim,
                    { role: 'user', content: userMessage } // 用户输入文本
                ]
            })
        });

        if (!response.ok) {
            throw new Error(`AI功能出现问题: ${response.status}`);
        }

        const data = await response.json();

        if (data.choices && data.choices[0]) 
            {
                const {role:newSender,content:newContent} = data.choices[0].message;
                await Promise.all([
                    await pool.query(
                    `INSERT INTO messages(conversation_id,sender,content) VALUES(?,?,?)`,
                    [conversationId,'user',userMessage]
                    ),
                    pool.query(
                    `INSERT INTO messages(conversation_id,sender,content) VALUES(?,?,?)`,
                    [conversationId,newSender,newContent]
                    )
                ]);
                res.status(200).json({ 
                    code:200,
                    msg:'AI回复成功',
                    data: data.choices[0].message 
                });
            }else {
                res.status(210).json('未能获取到AI回复');
            }

    }catch(error)
    {
        res.status(500).json(error.message)
    }
}

//文字转语音（已登录，需要‘转语音的文本内容’，‘语音模型’）
export async function TTS_audioTransform(req,res){
    try{
        const {contentText,voiceType}=req.body;
        const pattern = /(\([^()]*\)|\[[^\[\]]*\]|\{[^\{\}]*\}|（[^（）]*）|［[^［］]*］|｛[^｛｝]*｝|【[^【】]*】)/g;
        let cleanedText = contentText.replace(pattern, '');
        cleanedText = cleanedText.replace(/\s+/g, ' ').trim();

        const audioResponse = await fetch('https://openai.qiniu.com/v1/voice/tts', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`
                },
                body: JSON.stringify({
                    audio: {
                        voice_type: `${voiceType}`,
                        encoding: "mp3",
                        speed_ratio: 1.0
                    },
                    request: {
                        text: cleanedText
                    }
                })
            })
        
        if (!audioResponse.ok) {
            throw new Error(`语音功能出现问题: ${audioResponse.status}`);
        }

        const audioData =await audioResponse.json();

        return res.status(200).json({
            code:200,
            msg:'语音转换成功',
            data:{
                audioData:audioData
            }
        })
         
    }catch(error){
        return res.status(500).json(error.message)
    }
    
}